import java.io.*
import java.lang.Exception
import java.net.Socket

fun main(args: Array<String>) {
    println("-----------Client启动...--------------")
    val client=Socket("localhost",8889)
    val userName=getUserName()
    println("${userName},您已进入聊天室,请在控制台中输入消息进行聊天")
    Thread(ClientSendMsg(client,userName)).start()
    Thread(ClientReceiveMsg(client)).start()
}

fun getUserName():String{
    val get=BufferedReader(InputStreamReader(System.`in`))
    var userName=""
    println("请输入用户名,用户名不可为空")
    while(userName == ""){
        userName=get.readLine()
    }
    return userName
}
//客户端发送消息
class ClientSendMsg(private var client:Socket):Runnable{
    lateinit var userName:String
    constructor(client: Socket,userName: String) : this(client){
        this.userName=userName
    }
    private val console=BufferedReader(InputStreamReader(System.`in`))
    private val dos=DataOutputStream(client.getOutputStream())
    var isOnline =true
    override fun run() {
        while (isOnline){
            var msg=console.readLine()
                if(msg!=null&&!msg.equals("")){
                    msg="${this.userName}说:${msg}"
                    try {
                        dos.writeUTF(msg)
                        dos.flush()
                    }catch (e:Exception){
                        println("client error code:1")
                        ChatUtils.release(client,console,dos)
                    }
                }
        }
    }
}
//客户端接受消息
class ClientReceiveMsg(private var client: Socket):Runnable{
    private val dis =DataInputStream(client.getInputStream())
    override fun run() {
        while (true){
            var info=""
            try {
                var info=dis.readUTF()
                println(info)
            }catch (e:Exception){
                println("client error code:2")
                ChatUtils.release(client,dis)
            }
        }
    }
}